﻿using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceProcess;
using Microsoft.Practices.Unity;
using SpectrumAnalyser.Common.Hosting;
using SpectrumAnalyser.Config.Contract;
using SpectrumAnalyser.ModelObjects.Enum;

namespace SpectrumAnalyser.Config.Service
{
    public class ConfigService : ServiceBase
    {
        private readonly IUnityContainer _unityContainer;
        private ServiceHost _host;

        public ConfigService(IUnityContainer unityContainer)
        {
            this._unityContainer = unityContainer;
        }

        private void CreateHost()
        {
            var configService = this._unityContainer.Resolve<IConfigService>();

            var hostUri = WcfHelper.GetEndpointUri(UriScheme.Http, "IConfigService");
            this._host = new ServiceHost(configService, hostUri);

            _host.AddServiceEndpoint(typeof(IConfigService), WcfHelper.GetBinding(UriScheme.Http), "");

            foreach (ServiceEndpoint endpoint in this._host.Description.Endpoints)
            {
                foreach (OperationDescription operation in endpoint.Contract.Operations)
                {
                    var dataContractBehavior = operation.Behaviors.Find<DataContractSerializerOperationBehavior>();
                    if (dataContractBehavior != null)
                    {
                        dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                    }
                }
            }

            this._host.Open();
        }

        protected override void OnStart(string[] args)
        {
            CreateHost();
            base.OnStart(args);
        }

        protected override void OnStop()
        {
            _host.Close();
            base.OnStop();
        }
    }
}